package com.hhsj.androidserver;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class HttpServer {
    private final static int DEFULT_PORT = 8080;               //默认端口
    private boolean isShudown = false;            //服务状态
    private ServerSocketChannel ssc;
    private int mPort = HttpServer.DEFULT_PORT;

    private AtomicInteger integer = new AtomicInteger(0);

    private ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 128, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, integer.incrementAndGet() + "");
        }
    }, new RejectedExecutionHandler() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

        }
    });

    public static HttpServer create() {
        return new HttpServer();
    }

    private HttpServer() {
    }

    public HttpServer port(int port) {
        mPort = port;
        return this;
    }

    public void start() {
        try {
            ssc = ServerSocketChannel.open(); // 打开服务器套接字通道
            ssc.socket().bind(new InetSocketAddress(mPort));     //绑定到特定端口
            ssc.configureBlocking(false);                      //设置为非阻塞模式
            Selector selector = Selector.open();                 //打开一个选择器

            System.err.println("HttpServer selector = " + selector);

            //ServerSocketChannel 只能注册 SelectionKey.OP_ACCEPT
            ssc.register(selector, SelectionKey.OP_ACCEPT);    //向给定的选择器注册此通道，返回一个选择键
            while (true) {
                System.err.println("HttpServer selector = " + selector);

                synchronized (this) {
                    if (isShudown) {
                        System.err.println("HttpServer 结束");
                        break;
                    }
                }
                try {
                    int keysNum = selector.select();
                    System.err.println("HttpServer selector.select() = " + keysNum);

                    if (keysNum > 0) {        //等待请求，请求过来继续执行，没有请求一直等待
                        final Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();          //获取等待处理的请求
                        while (keyIter.hasNext()) {
                            SelectionKey key = keyIter.next();
                            keyIter.remove();
                            /**
                             * 异步并发有点问题，这里先采用同步
                             */
//                            executor.execute(new HttpHandler(key)); // 启动新线程处理SelectionKey
                            new HttpHandler(key).run();
                        }
                    }
                } catch (Exception e) {

                }

            }
        } catch (IOException e) {

        }

    }


    /**
     * 关闭端口
     *
     * @throws IOException
     */
    public void stop() {
        synchronized (this) {
            isShudown = true;
        }
        try {
            if (null != ssc) {
                ssc.socket().close();
            }
        } catch (Exception E) {

        }
    }


}